<?php  
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 
 * 后台系统配置模型类
 * @author 66diqiu-li
 *
 */
class Admin_Shopconfig_model extends CI_Model {

	/**
     * @var
     */
    private $table;

    /**
     * @var
     */
    private $table_site;

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        $this->table      = $this->db->dbprefix("shop_config");
        $this->table_site = $this->db->dbprefix("shop_config_site");
        $this->table_line = $this->db->dbprefix("line");
    }

    public function get_key_value($sid, $key_code = '')
    {
        $this->db->select('key_code,key_value');
        if(!empty($sid))$this->db->where(array('sid'=>$sid, 'key_code' => $key_code));
        $query = $this->db->get($this->table_site);
        $data = $query->row_array();
        return $data['key_value'];
    }

    /**
	 * 批量更新系统设置
     * @param $sid 站点ID
     * @param $data 更新数据
     * @return bool
	 */
    function update_batch($sid,$data){

        //判断是否存在数据
        $old_data = $this->get_info($sid);
	    if(!empty($data)){
            if($old_data){
                $insert_data = array();
	            foreach($data as $key=>$val){

                    //不存在原先数据时 添加数据
                    if(!isset($old_data[$key])){
                        $insert_data[] = array('sid'=>$sid,'key_code'=>$key,'key_value'=>$val);
                        continue;
                    }
                    //存在数据,但值不同时更新数据
                    if($val!=$old_data[$key]){
                        if($key=='conn_sites'){
                            $new = explode(",",$val);
                            $old = explode(",",$old_data[$key]);
                            $differ = array_diff($old,$new);
                            if($differ){
                                $differ_ids = implode(",",array_values($differ));
                                if($differ_ids){
                                    $this->db->query("update $this->table_line set is_del=1 where sid in ($differ_ids) and conn_line_id<>0 ");
                                }
                            }
                        }
                        $row = array('key_value'=>$val);
                        $this->db->update($this->table_site, $row, array('sid'=>$sid,'key_code'=>$key));
                    }
                }
                if(!empty($insert_data)){
                    return $this->db->insert_batch($this->table_site, $insert_data);
                }
                return true;
            }else{
                    //添加数据
                $insert_data = array();
                foreach($data as $key=>$val){
                    $insert_data[] = array('sid'=>$sid,'key_code'=>$key,'key_value'=>$val);
                }
                return $this->db->insert_batch($this->table_site, $insert_data);
            }
        }else {
            return false;
        }
	}
	
	/**
     * 获取站点的基本配置结构
     * @param int $sid 站点ID
     * @return array 返回数组
	 */
    function get_list($sid=0){
        $this->db->select('id,varname,info,groupid,value');
        $query = $this->db->get($this->table);
        $data = array();
        $sid_data = array();
        if($sid) $sid_data = $this->get_info($sid);
        foreach($query->result_array() as $row){
            $data[$row['varname']] = $row;
            if(isset($sid_data[$row['varname']]))$data[$row['varname']]['value'] = @$sid_data[$row['varname']];
        }        
        return $data;
	}
	
    /**
     * 获取某个站点的基本配置信息
     * @param $sid
     * @return mixed
     */
    function get_info($sid){
        static $siteinfo;
        if($siteinfo[$sid]){
            return $siteinfo[$sid];
        }
        $this->db->select('key_code,key_value');
        if(!empty($sid))$this->db->where(array('sid'=>$sid), NULL, FALSE);
        $query = $this->db->get($this->table_site);
        $data = array();
        foreach($query->result_array() as $row){
            $data[$row['key_code']] = $row['key_value'];
        }
        $data['auth_sites'] = $this->get_auth_sites($sid);//可以获取线路的站点
        $siteinfo[$sid] = $data;
        return $data;
    }

	/**
	 * 
	 * 获取具有权限的供应商网站的站点ids
	 * @param $sid
	 */
    function get_auth_sites($sid=0){
    	$sql = "select sid from ".$this->table_site." where key_code='dis_sites' and find_in_set($sid,key_value)";
    	$query = $this->db->query($sql);
    	$result = $query->result_array();
    	$str = '';
    	foreach($result as $val){
    		$str.=",".$val['sid'];
    	}
    	return trim($str,",");
    }

    /**
     * 获取网站的站点基本信息 ，并生成新的常量配置
     * @param $data
     */
    function set_basice_info($data){
        static $set_basice_info;
        $key_ = md5(serialize($data));
        if($set_basice_info[$key_]){
            return $set_basice_info[$key_];
        }
        //获取城市名称
        $area_name = '';
        $city_id = '1602';
        if(isset($data['sitecity'])){
            $area_name = str_replace(array('[',']'),'',$this->area_model->get_area_name(array($data['sitecity'])));
            $city_id = $data['sitecity'];
        }else{
            $area_name = '南京';
        }

        if(isset($data['sitedistrict'])){
            $area_name.= str_replace(array('[',']'),'',$this->area_model->get_area_name(array($data['sitedistrict'])));
        }else{
            $area_name = '南京';
        }

        //获取省份名称
        $province_name = '';
        $procince_id = '1600';
        if(isset($data['siteprovince'])){
            $province_name = str_replace(array('[',']'),'',$this->area_model->get_area_name(array($data['siteprovince'])));
            $procince_id = $data['siteprovince'];
        }else{
            $province_name = '江苏';
        }

        $data['sitecityname'] = $area_name;
        $data['sitecity'] = $city_id;
        $data['siteprovincename'] = $province_name;
        $data['siteprovince'] = $procince_id;
        $data['site_template'] = isset($data['site_template'])?$data['site_template']:'bz06';
        $set_basice_info[$key_] = $data;
        return $data;
    }

    /**获取站点所在城市，所有站点
     * @return mixed
     */
    function get_site_city_ids(){
        $sql = "select sid from ".$this->table_site." where key_code='sitecity' and key_value=".SITECITY;
        $query = $this->db->query($sql);
        $result = $query->result_array();
        if($result){
            foreach($result as $k=>$v)
            {
                $sid[$k] = $v['sid'];
            }
        }
        return $sid;
    }

    /**
     * 根据查询条件获取站点ID
     * @param string $where
     * @return array
     */
    public function get_sid_for_city($where=''){
        if(isset($where['city_id'])&&$where['city_id']!='-1'){
            $sql = "SELECT sid FROM ".$this->table_site." WHERE key_code='sitecity' AND key_value=".$where['city_id']."";
        }else{
            $sql = "SELECT sid FROM ".$this->table_site." WHERE key_code='siteprovince' AND key_value=".$where['province_id']."";
        }
        $query = $this->db->query($sql);
        $result = $query->result_array();
        $sids = implode(',',array_map(array_shift,$result));
        $resData = array();
        if($sids){
            $table = $this->db->dbprefix("siteinfo");
            $sql = "SELECT sid,name FROM {$table} WHERE sid in ({$sids}) AND type='分销商'";
            $query = $this->db->query($sql);
            $resData = $query->result_array();
        }
        return $resData;
    }

    /**
     * 根据站点ID获取相应的网站信息
     * @param $sids
     */
    public function get_site_list($sids){
        $table = $this->db->dbprefix("siteinfo");
        if($sids !==null){
            if($sids==''){
                $sids='0';
            }
        }
        $sql = "SELECT sid,name FROM {$table} WHERE sid in ({$sids})";
        $query = $this->db->query($sql);
        $resData = $query->result_array();
        return $resData;
    }

    /**
     * 判断站点是否为免维护附属站点
     * @param $sid
     */
    function  check_site($sid){
        if(empty($sid)){
            return false;
        }
        $sql = "select 1 from ".$this->table_site." where key_code='conn_sites' and FIND_IN_SET($sid,key_value)";
        $query = $this->db->query($sql);
        $res = $query->row_array();
        return $res;
    }
}